﻿// Apache-2.0 License
// Copyright (c) 2021-2022 SuperJeff
// 微信:15906588664  QQ:1024489

using Admin.Net.InformationPlatform.Const;
using Furion;
using Furion.DependencyInjection;
using Microsoft.AspNetCore.Mvc;
using NewLife.Caching;
using System.Security.Claims;

namespace Admin.Net.InformationPlatform.Service.Cache;
/// <summary>
/// 缓存管理办法
/// </summary>
public class InformationSysCacheService : ISingleton
{
    private readonly ICache _cache;

    /// <summary>
    /// 缓存管理办法 
    /// </summary>
    /// <param name="cache"></param>
    public InformationSysCacheService(ICache cache)
    {
        _cache = cache;
    }
    /// <summary>
    /// 获取任务ID缓存集合
    /// </summary>
    /// <param name="taskId"></param>
    /// <returns></returns>
    public CacheTask GetTaskId(string taskId)
    {
        var key = Const.CacheConst.KeyTaskIdList + taskId;
        return _cache.Get<CacheTask>(key);
    }

    /// <summary>
    /// 增加缓存任务ID
    /// </summary>
    /// <param name="taskId">任务ID</param>
    /// <param name="taskInfo">任务信息</param>
    /// <returns></returns>
    public bool SetTaskId(string taskId, CacheTask taskInfo)
    {
        var key = Const.CacheConst.KeyTaskIdList + taskId;
        return _cache.Set(key, taskInfo);
    }

    /// <summary>
    /// 增加缓存任务ID
    /// </summary>
    /// <param name="taskId">任务ID</param>
    /// <param name="taskInfo">任务信息</param>
    /// <param name="expire">超过多少时间不调用就失效，单位是秒</param>
    /// <returns></returns>
    public bool SetTaskId(string taskId, CacheTask taskInfo, long expire)
    {
        var key = Const.CacheConst.KeyTaskIdList + taskId;
        return _cache.Set(key, taskInfo, TimeSpan.FromSeconds(expire));
    }
    /// <summary>
    /// 删除缓存
    /// </summary>
    /// <param name="taskId"></param>
    /// <returns></returns>
    public int RemoveTaskId(string taskId)
    {
        var key = Const.CacheConst.KeyTaskIdList + taskId;
        return _cache.Remove(key);
    }

    /// <summary>
    /// 检查缓存是否存在
    /// </summary>
    /// <param name="taskId">键</param>
    /// <returns></returns>
    [NonAction]
    public bool ExistKeyTaskId(string taskId)
    {
        var key = Const.CacheConst.KeyTaskIdList + taskId;
        return _cache.ContainsKey(key);
    }
    /// <summary>
    /// 判断token
    /// </summary>
    /// <returns></returns>
    [NonAction]
    public bool JudgeUserToken()
    {
        return App.HttpContext.Request.Headers.Authorization.ToString().Equals($"Bearer {_cache.Get<string>($"userID:{App.User?.FindFirstValue("UserName") ?? ""}")}");

    }

}
